package com.topcent.tioxyc.service;

import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.vo.GameRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;
import java.util.Scanner;

/**
 * @author: 陈百万
 * @date: 2025/3/19 14:17
 * @Description: 游戏控制台输入类
 */
@RestController
public class GuessSizeGame {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @GetMapping("/game")
    public String startGame() {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        System.out.print("请输入玩家ID：");
        int playerId = scanner.nextInt();

        while (true) {
            BigDecimal balance = getBalance(playerId);
            System.out.println("当前余额：" + balance);
            System.out.print("请输入下注金额：");
            BigDecimal betAmount = scanner.nextBigDecimal();

            if (betAmount.compareTo(balance) > 0) {
                System.out.println("余额不足，无法下注！请联系管理员充值");
                break;
            }

            System.out.print("请选择大小（大1/小0）：");
            String betChoice = scanner.next();

            int dice = random.nextInt(6) + 1;
            String result = (dice >= 4) ? "1" : "0";
            boolean isWin = betChoice.equals(result);

            BigDecimal earnings = isWin ? betAmount : betAmount.negate();
            balance = balance.add(earnings);

            GameRecord record = new GameRecord();
            record.setPlayerId(playerId);
            record.setCreateTime(new Date());
            record.setBetAmount(betAmount);
            record.setBetChoice(betChoice);
            record.setResult(isWin ? "胜利" : "失败");
            record.setEarnings(earnings);
            record.setBalance(balance);

            yy1KpiMapper.insertGameRecord(record);

            System.out.println("骰子点数：" + dice + "，结果：" + result);
            System.out.println(isWin ? "恭喜，你赢了！" : "很遗憾，你输了！");
            System.out.println("当前余额：" + balance);

            System.out.print("是否继续游戏？（1/0）：");
            String continueGame = scanner.next();
            if (!"1".equalsIgnoreCase(continueGame)) {
                break;
            }
        }
//        scanner.close();
        System.out.println("游戏结束！");
        return "游戏结束！";
    }

    // 获取玩家余额
    private BigDecimal getBalance(int playerId) {
        BigDecimal balance = yy1KpiMapper.getLatestBalance(playerId);
        return (balance != null) ? balance : BigDecimal.ZERO;
    }
}
